﻿using Model.Util.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Services.Util;
using Model.Util;
using Xproject.Util;
using Model.Admin;
using System.IO;

namespace WeiXinpProAdmin.Controllers
{
    public class CategoryController : AdminBaseController
    {

        CategoryServices m_CategoryServices;
        IndexCategoryServices m_IndexCategoryServices;
        public CategoryController(CategoryServices mCategoryServices, IndexCategoryServices mIndexCategoryServices)
        {
            m_CategoryServices = mCategoryServices;
            m_IndexCategoryServices = mIndexCategoryServices;
        }


        // GET: Category
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult CategoryList()
        {
            CategoryListModel model = new CategoryListModel();
            model.CategoryList = m_CategoryServices.GetAllCategory();
           
            return View(model);
           
        }

        /// <summary>
        /// 添加分类
        /// </summary>      
        public ViewResult AddCategory()
        {
            Category model = new Category();
            Load();
            return View(model);
        }

        /// <summary>
        /// 添加分类
        /// </summary>
        [HttpPost]
        public JsonResult AddCategory(Category model)
        {
            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;
            if (m_CategoryServices.GetCateIdByName(model.Name) > 0)
                result="名称已经存在";

            if (model.ParentId != 0 && m_CategoryServices.GetCategoryById(model.ParentId) == null)
                result="父分类不存在";

            if (ModelState.IsValid)
            {
                Category categoryInfo = new Category()
                {
                    DisplayOrder = model.DisplayOrder,
                    Name = model.Name,
                    ParentId = model.ParentId,
                    PriceRange = CommonHelper.StringArrayToString(CommonHelper.RemoveArrayItem(CommonHelper.SplitString(CommonHelper.TBBRTrim(model.PriceRange).Replace("，", ","))))
                };

                m_CategoryServices.CreateCategory(categoryInfo);
                success = true;
               // AddMallAdminLog("添加分类", "添加分类,分类为:" + model.CategroyName);                
            }

            result = (success) ? "编辑分类成功！" : "编辑失败！";
            jsonData = new { Success = success, Data = result };
            return Json(jsonData, JsonRequestBehavior.AllowGet);                          
        }

        /// <summary>
        /// 编辑分类
        /// </summary>
        [HttpGet]
        public ActionResult EditCategory(int cateId = -1)
        {
            Category categortInfo = m_CategoryServices.GetCategoryById(cateId);
            //if (categortInfo == null)
            //    return PromptView("此分类不存在");

            //Category model = new Category();
            //model.Name = categortInfo.Name;
            //model.ParentId = categortInfo.ParentId;
            //model.DisplayOrder = categortInfo.DisplayOrder;
            //model.PriceRange = categortInfo.PriceRange;

            Load();
            return View(categortInfo);
        }

        /// <summary>
        /// 编辑分类
        /// </summary>
        [HttpPost]
        public JsonResult EditCategory(Category model, int cateId = -1)
        {
            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;
            Category categoryInfo = m_CategoryServices.GetCategoryById(cateId);
           // if (categoryInfo == null)
            //    return PromptView("此分类不存在");

            int cateId2 = m_CategoryServices.GetCateIdByName(model.Name);
            if (cateId2 > 0 && cateId2 != cateId)
                result="名称已经存在";

            if (model.ParentId == categoryInfo.CategoryID)
                result= "不能将自己作为父分类";

            if (model.ParentId != 0 && m_CategoryServices.GetCategoryById(model.ParentId) == null)
                result="父分类不存在";

            if (model.ParentId != 0 && m_CategoryServices.GetChildCategoryList(categoryInfo.CategoryID, categoryInfo.Layer, true).Exists(x => x.CategoryID == model.ParentId))
                result= "不能将分类调整到自己的子分类下";

            if (ModelState.IsValid)
            {
                int oldParentId = categoryInfo.ParentId;

                categoryInfo.DisplayOrder = model.DisplayOrder;
                categoryInfo.Name = model.Name;
                categoryInfo.ParentId = model.ParentId;
                categoryInfo.PriceRange = CommonHelper.StringArrayToString(CommonHelper.RemoveArrayItem(CommonHelper.SplitString(CommonHelper.TBBRTrim(model.PriceRange).Replace("，", ","))));

              success=  m_CategoryServices.UpdateCategory(categoryInfo, oldParentId);
              //  AddMallAdminLog("修改分类", "修改分类,分类ID为:" + cateId);
               // return PromptView("商品修改成功");
            }

            result = (success) ? "编辑分类成功！" : "编辑分类失败！";
            jsonData = new { Success = success, Data = result };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 删除分类
        /// </summary>
        public JsonResult DelCategory(int cateId = -1)
        {
            var jsonData = new Object();
            string resultStr = string.Empty;
            bool success = false;
            int result = m_CategoryServices.DeleteCategoryById(cateId);
            if (result == -3)
                resultStr = ("分类不存在");
            if (result == -2)
                resultStr =("删除失败，请先转移或删除此分类下的子分类");
            if (result == -1)
                resultStr = ("删除失败，请先删除此分类下的属性分组");
            if (result == 0)
                resultStr=("删除失败，请先转移或删除此分类下的商品");
            // AddMallAdminLog("删除分类", "删除分类,分类ID为:" + cateId);
            if (result == 1)
            {
                resultStr = ("删除成功");
                success = true;
            }
                jsonData = new { Success = success, Data = resultStr };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        private void Load()
        {
            ViewData["categoryList"] = m_CategoryServices.GetAllCategory();
           // ViewData["referer"] = MallUtils.GetMallAdminRefererCookie();
        }


        /// <summary>
        /// 属性分组列表
        /// </summary>
        public ActionResult AttributeGroupList(int cateId = -1)
        {
            Category categoryInfo = m_CategoryServices.GetCategoryById(cateId);
           // if (categoryInfo == null)
           //     return PromptView("分类不存在");

            AttributeGroupListModel model = new AttributeGroupListModel()
            {
                AttributeGroupList = m_CategoryServices.GetAttributeGroupListByCateId(cateId,null),
                CateId = cateId,
                CategoryName = categoryInfo.Name
            };
           // MallUtils.SetAdminRefererCookie(string.Format("{0}?cateId={1}", Url.Action("attributegrouplist"), cateId));
            return View(model);
        }

        /// <summary>
        /// 添加属性分组
        /// </summary>
        [HttpGet]
        public ActionResult AddAttributeGroup(int cateId = -1)
        {
            Category categoryInfo = m_CategoryServices.GetCategoryById(cateId);
           // if (categoryInfo == null)
           //     return PromptView("分类不存在");

            AttributeGroupModel model = new AttributeGroupModel();
            ViewData["cateId"] = categoryInfo.CategoryID;
            ViewData["categoryName"] = categoryInfo.Name;
            //ViewData["referer"] = MallUtils.GetMallAdminRefererCookie();
            return View(model);
        }

        /// <summary>
        /// 添加属性分组
        /// </summary>
        [HttpPost]
        public JsonResult AddAttributeGroup(AttributeGroupModel model, int cateId = -1)
        {
            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;
            Category categoryInfo = m_CategoryServices.GetCategoryById(cateId);
           // if (categoryInfo == null)
           //     return PromptView("分类不存在");

            if (m_CategoryServices.GetAttributeGroupIdByCateIdAndName(cateId, model.AttributeGroupName) > 0)
                result= "名称已经存在";

            if (ModelState.IsValid)
            {
                 
                CategoryAttrGroups attributeGroupInfo = new CategoryAttrGroups()
                {
                    Name = model.AttributeGroupName,
                    CategoryID = categoryInfo.CategoryID,
                    DisplayOrder = model.DisplayOrder,
                    CategoryType = model.CategoryType
                };

                success= m_CategoryServices.CreateAttributeGroup(attributeGroupInfo);
              //  AddMallAdminLog("添加属性分组", "添加属性分组,属性分组为:" + model.AttributeGroupName);
              //  return PromptView("属性分组添加成功");
            }
            result = (success) ? "添加分类群组成功！" : "添加分类群组失败！";
            jsonData = new { Success = success, Data = result };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }


        /// <summary>
        /// 编辑属性分组
        /// </summary>
        [HttpGet]
        public ActionResult EditAttributeGroup(int attrGroupId = -1)
        {
            CategoryAttrGroups attributeGroupInfo = m_CategoryServices.GetAttributeGroupById(attrGroupId);
            //if (attributeGroupInfo == null)
            //    return PromptView("属性分组不存在");

            AttributeGroupModel model = new AttributeGroupModel();
            model.AttributeGroupName = attributeGroupInfo.Name;
            model.DisplayOrder = attributeGroupInfo.DisplayOrder;
            model.CategoryType = attributeGroupInfo.CategoryType;
            Category categoryInfo = m_CategoryServices.GetCategoryById(attributeGroupInfo.CategoryID);
            ViewData["cateId"] = categoryInfo.CategoryID;
            ViewData["categoryName"] = categoryInfo.Name;
            ViewData["attrGroupId"] = attrGroupId;

           // ViewData["referer"] = MallUtils.GetMallAdminRefererCookie();

            return View(model);
        }

        /// <summary>
        /// 编辑属性分组
        /// </summary>
        [HttpPost]
        public JsonResult EditAttributeGroup(AttributeGroupModel model, int attrGroupId = -1)
        {
            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;
            CategoryAttrGroups attributeGroupInfo = m_CategoryServices.GetAttributeGroupById(attrGroupId);
          //  if (attributeGroupInfo == null)
          //      return PromptView("属性分组不存在");

            int attrGroupId2 = m_CategoryServices.GetAttributeGroupIdByCateIdAndName(attributeGroupInfo.CategoryID, model.AttributeGroupName);
            if (attrGroupId2 > 0 && attrGroupId2 != attrGroupId)
                result= "名称已经存在";

            if (ModelState.IsValid)
            {
                attributeGroupInfo.Name = model.AttributeGroupName;
                attributeGroupInfo.DisplayOrder = model.DisplayOrder;

               success= m_CategoryServices.UpdateAttributeGroup(attributeGroupInfo);
               // AddMallAdminLog("修改属性分组", "修改属性分组,属性分组ID为:" + attrGroupId);
               // return PromptView("属性分组修改成功");
            }

           // Category categoryInfo = m_CategoryServices.GetCategoryById(attributeGroupInfo.CategoryID);
            result = (success) ? "编辑分类群组成功！" : "编辑分类群组失败！";
            jsonData = new { Success = success, Data = result };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 删除属性分组
        /// </summary>
        public JsonResult DelAttributeGroup(int attrGroupId = -1)
        {
            var jsonData = new Object();
            string resultStr = string.Empty;
            bool success = false;
            int result = m_CategoryServices.DeleteAttributeGroupById(attrGroupId);
            if (result == 0)
                resultStr = ("删除失败，请先删除此属性分组下的属性");
            else {
                resultStr = ("删除成功");
                success = true;
            }
            //  AddMallAdminLog("删除属性分组", "删除属性分组,属性分组ID为:" + attrGroupId);
            jsonData = new { Success = success, Data = resultStr };
            return Json(jsonData, JsonRequestBehavior.AllowGet);

        }



        /// <summary>
        /// 属性列表
        /// </summary>
        public ActionResult AttributeList(string sortColumn, string sortDirection, int cateId = -1)
        {
            Category categoryInfo = m_CategoryServices.GetCategoryById(cateId);
           // if (categoryInfo == null)
           //     return PromptView("分类不存在");

            string sort = m_CategoryServices.AdminGetBrandListSort(sortColumn, sortDirection);

            AttributeListModel model = new AttributeListModel()
            {
                AttributeList = m_CategoryServices.AdminGetAttributeList(cateId, sort),
                SortColumn = sortColumn,
                SortDirection = sortDirection,
                CateId = cateId,
                CategoryName = categoryInfo.Name
            };

         //   MallUtils.SetAdminRefererCookie(string.Format("{0}?cateId={1}&sortColumn={2}&sortDirection={3}", Url.Action("attributelist"), cateId, sortColumn, sortDirection));
            return View(model);
        }


        /// <summary>
        /// 添加属性
        /// </summary>
        [HttpGet]
        public ActionResult AddAttribute(int cateId = -1)
        {
            Category categoryInfo = m_CategoryServices.GetCategoryById(cateId);
            //if (categoryInfo == null)
            //    return PromptView("分类不存在");

            AttributeModel model = new AttributeModel();
            ViewData["cateId"] = categoryInfo.CategoryID;
            ViewData["categoryName"] = categoryInfo.Name;
            ViewData["attributeGroupList"] = GetAttributeGroupSelectList(cateId);
           // ViewData["referer"] = MallUtils.GetMallAdminRefererCookie();
            return View(model);
        }
        /// <summary>
        /// 添加属性
        /// </summary>
        [HttpPost]
        public ActionResult AddAttribute(AttributeModel model, int cateId = -1)
        {
            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;
            Category categoryInfo = m_CategoryServices.GetCategoryById(cateId);
            //if (categoryInfo == null)
             //   return PromptView("分类不存在");

            if (m_CategoryServices.GetAttrIdByCateIdAndName(cateId, model.AttributName) > 0)
                result="名称已经存在";

            CategoryAttrGroups attributeGroupInfo = m_CategoryServices.GetAttributeGroupById(model.AttrGroupId);
            if (attributeGroupInfo == null || attributeGroupInfo.CategoryID != cateId)
                result= "属性组不存在";

            if (ModelState.IsValid)
            {
                CategoryAttr attributeInfo = new CategoryAttr();
                attributeInfo.Name = model.AttributName;
                attributeInfo.CategoryID = cateId;
                attributeInfo.AttrGroupId = model.AttrGroupId;
                attributeInfo.ShowType = model.ShowType;
                attributeInfo.Isfilter = model.IsFilter;
                attributeInfo.DisplayOrder = model.DisplayOrder;

                success = m_CategoryServices.CreateAttribute(attributeInfo, attributeGroupInfo);
                //AddMallAdminLog("添加分类属性", "添加分类属性,属性为:" + model.AttributName);
                //return PromptView("分类属性添加成功");
            }
            result = (success) ? "添加分类属性成功！" : "添加分类属性失败！";
            jsonData = new { Success = success, Data = result };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 编辑属性
        /// </summary>
        [HttpGet]
        public ActionResult EditAttribute(int attrId = -1)
        {
            CategoryAttr attributeInfo = m_CategoryServices.GetAttributeById(attrId);
           // if (attributeInfo == null)
           //     return PromptView("属性不存在");

            AttributeModel model = new AttributeModel();
            model.AttributName = attributeInfo.Name;
            model.AttrGroupId = attributeInfo.AttrGroupId;
            model.ShowType = attributeInfo.ShowType;
            model.IsFilter = attributeInfo.Isfilter;
            model.DisplayOrder = attributeInfo.DisplayOrder;

            Category categoryInfo = m_CategoryServices.GetCategoryById(attributeInfo.CategoryID);
            ViewData["cateId"] = categoryInfo.CategoryID;
            ViewData["categoryName"] = categoryInfo.Name;
            ViewData["attributeGroupList"] = GetAttributeGroupSelectList(categoryInfo.CategoryID);
            ViewData["attrId"] = attributeInfo.AttrId;
            //  ViewData["referer"] = MallUtils.GetMallAdminRefererCookie();

            return View(model);
        }

        /// <summary>
        /// 编辑属性
        /// </summary>
        [HttpPost]
        public JsonResult EditAttribute(AttributeModel model, int attrId = -1)
        {
            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;
            CategoryAttr attributeInfo = m_CategoryServices.GetAttributeById(attrId);
           // if (attributeInfo == null)
           //     return PromptView("属性不存在");

            int attrId2 = m_CategoryServices.GetAttrIdByCateIdAndName(attributeInfo.CategoryID, model.AttributName);
            if (attrId2 > 0 && attrId2 != attrId)
                result="名称已经存在";

            CategoryAttrGroups attributeGroupInfo = m_CategoryServices.GetAttributeGroupById(model.AttrGroupId);
            if (attributeGroupInfo == null || attributeGroupInfo.CategoryID != attributeInfo.CategoryID)
                result="属性组不存在";

            if (ModelState.IsValid)
            {
                attributeInfo.Name = model.AttributName;
                attributeInfo.AttrGroupId = model.AttrGroupId;
                attributeInfo.Isfilter = model.IsFilter;
                attributeInfo.ShowType = model.ShowType;
                attributeInfo.DisplayOrder = model.DisplayOrder;

                success= m_CategoryServices.UpdateAttribute(attributeInfo);
                //AddMallAdminLog("编辑分类属性", "编辑分类属性,分类属性ID为:" + attrId);
                //return PromptView("分类属性修改成功");
            }

            result = (success) ? "编辑分类属性成功！" : "编辑分类属性失败！";
            jsonData = new { Success = success, Data = result };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 删除属性
        /// </summary>
        public ActionResult DelAttribute(int attrId)
        {
            var jsonData = new Object();
            string resultStr = string.Empty;
            bool success = false;
            int result = m_CategoryServices.DeleteAttributeById(attrId);
            if (result == 0)
                resultStr=("删除失败，请先删除此属性下的属性值");
            else {
                success = true;
                resultStr = ("删除成功");
            }
            jsonData = new { Success = success, Data = resultStr };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 获得分类的属性及其值json列表
        /// </summary>
        /// <param name="cateId">分类id</param>
        /// <returns></returns>
        public ContentResult AAndVJsonList(int cateId = -1)
        {
            return Content(m_CategoryServices.GetCategoryAAndVListJsonCache(cateId));
        }

        private List<SelectListItem> GetAttributeGroupSelectList(int cateId)
        {
            List<SelectListItem> itemList = new List<SelectListItem>();
            List<CategoryAttrGroups> attributeGroupList = m_CategoryServices.GetAttributeGroupListByCateId(cateId,null);
            itemList.Add(new SelectListItem() { Text = "请选择分类", Value = "0" });
            foreach (CategoryAttrGroups attributeGroupInfo in attributeGroupList)
            {
                itemList.Add(new SelectListItem() { Text = attributeGroupInfo.Name, Value = attributeGroupInfo.AttrGroupId.ToString() });
            }
            return itemList;
        }
        /// <summary>
        /// 属性值列表
        /// </summary>
        public ActionResult AttributeValueList(int attrId = -1)
        {
            CategoryAttr attributeInfo = m_CategoryServices.GetAttributeById(attrId);
           // if (attributeInfo == null)
           //     return PromptView("属性不存在");

            AttributeValueListModel model = new AttributeValueListModel()
            {
                AttributeValueList = m_CategoryServices.GetAttributeSelectValueListByAttrId(attrId),
                AttrId = attributeInfo.AttrId,
                AttributeName = attributeInfo.Name,
                CateId = attributeInfo.CategoryID
            };
          //  MallUtils.SetAdminRefererCookie(string.Format("{0}?attrId={1}", Url.Action("attributevaluelist"), attrId));
            return View(model);
        }

        /// <summary>
        /// 添加属性值
        /// </summary>
        [HttpGet]
        public ActionResult AddAttributeValue(int attrId = -1)
        {
          
            CategoryAttr attributeInfo = m_CategoryServices.GetAttributeById(attrId);
            //if (attributeInfo == null)
            //    return PromptView("属性不存在");

            AttributeValueModel model = new AttributeValueModel();
            ViewData["attrId"] = attributeInfo.AttrId;
            ViewData["attributeName"] = attributeInfo.Name;
           // ViewData["referer"] = MallUtils.GetMallAdminRefererCookie();
            return View(model);
        }

        /// <summary>
        /// 添加属性值
        /// </summary>
        [HttpPost]
        public JsonResult AddAttributeValue(AttributeValueModel model, int attrId = -1)
        {
            var jsonData = new Object();
            string resultStr = string.Empty;
            bool success = false;
            CategoryAttr attributeInfo = m_CategoryServices.GetAttributeById(attrId);
            if (attributeInfo == null)
                resultStr= "属性不存在";

            if (m_CategoryServices.GetAttributeValueIdByAttrIdAndValue(attrId, model.AttrValue) > 0)
                resultStr="值已经存在";


            if (ModelState.IsValid)
            {
                CategoryAttrGroups attributeGroupInfo = m_CategoryServices.GetAttributeGroupById(attributeInfo.AttrGroupId);
                CategoryAttrValues attributeValueInfo = new CategoryAttrValues();

                attributeValueInfo.AttrId = attributeInfo.AttrId;
                attributeValueInfo.AttrName = attributeInfo.Name;
                attributeValueInfo.AttrDisplayOrder = attributeInfo.DisplayOrder;
                attributeValueInfo.AttrShowType = attributeInfo.ShowType;

                attributeValueInfo.AttrGroupId = attributeGroupInfo.AttrGroupId;
                attributeValueInfo.AttrGroupName = attributeGroupInfo.Name;
                attributeValueInfo.AttrGroupDisplayOrder = attributeGroupInfo.DisplayOrder;

                attributeValueInfo.AttrValue = model.AttrValue;
                attributeValueInfo.Isinput = 0;
                attributeValueInfo.AttrValueDisplayOrder = model.DisplayOrder;

                success=m_CategoryServices.CreateAttributeValue(attributeValueInfo);
                //AddMallAdminLog("添加属性值", "添加属性值,属性值为:" + model.AttrValue);
               // return PromptView("属性值添加成功");
            }
            resultStr = (success) ? "添加属性值成功！" : "添加属性值失败！";
            jsonData = new { Success = success, Data = resultStr };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 编辑属性值
        /// </summary>
        [HttpGet]
        public ActionResult EditAttributeValue(int attrValueId = -1)
        {
            CategoryAttrValues attributeValueInfo = m_CategoryServices.GetAttributeValueById(attrValueId);
           // if (attributeValueInfo == null)
           //     return PromptView("属性值不存在");
           // if (attributeValueInfo.IsInput == 1)
           //     return PromptView("输入型属性值不能修改");

            AttributeValueModel model = new AttributeValueModel();
            model.AttrValue = attributeValueInfo.AttrValue;
            model.DisplayOrder = attributeValueInfo.AttrValueDisplayOrder;

            CategoryAttr attributeInfo = m_CategoryServices.GetAttributeById(attributeValueInfo.AttrId);
            ViewData["attrId"] = attributeInfo.AttrId;
            ViewData["attributeName"] = attributeInfo.Name;
            ViewData["attrValueId"] = attrValueId;
           // ViewData["referer"] = MallUtils.GetMallAdminRefererCookie();

            return View(model);
        }

        /// <summary>
        /// 编辑属性值
        /// </summary>
        [HttpPost]
        public JsonResult EditAttributeValue(AttributeValueModel model, int attrValueId = 0)
        {
            var jsonData = new Object();
            string resultStr = string.Empty;
            bool success = false;
            CategoryAttrValues attributeValueInfo = m_CategoryServices.GetAttributeValueById(attrValueId);
            //if (attributeValueInfo == null)
            //    return PromptView("属性值不存在");
            //if (attributeValueInfo.IsInput == 1)
            //    return PromptView("输入型属性值不能修改");

            int attrValueId2 = m_CategoryServices.GetAttributeValueIdByAttrIdAndValue(attributeValueInfo.AttrId, model.AttrValue);
            if (attrValueId2 > 0 && attrValueId2 != attrValueId)
                resultStr="值已经存在";

            if (ModelState.IsValid)
            {
                attributeValueInfo.AttrValue = model.AttrValue;
                attributeValueInfo.AttrValueDisplayOrder = model.DisplayOrder;
              success=  m_CategoryServices.UpdateAttributeValue(attributeValueInfo);
               // AddMallAdminLog("修改属性值", "修改属性值,属性值ID为:" + attrValueId);
               // return PromptView("属性值修改成功");
            }

            resultStr = (success) ? "编辑属性值成功！" : "编辑属性值失败！";
            jsonData = new { Success = success, Data = resultStr };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 删除属性值
        /// </summary>
        public JsonResult DelAttributeValue(int attrValueId = -1)
        {
            var jsonData = new Object();
            string resultStr = string.Empty;
            bool success = false;
            int result = m_CategoryServices.DeleteAttributeValueById(attrValueId);
            if (result == -2)
                resultStr=("删除失败，此属性值不存在");
            if (result == -1)
                resultStr=("删除失败，此属性值不存在");
            if (result == 0)
                resultStr=("删除失败，请先删除此属性值下的商品");           
            else
            {
                success = true;
                resultStr = ("删除成功");
            }
            jsonData = new { Success = success, Data = resultStr };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        #region ActionResult 
        public ActionResult IndexCategoryList()
        {
            return View();
        }

        public ActionResult IndexCategoryEdit(string Id)
        {
            ViewData["categoryList"] = m_CategoryServices.GetAllCategory();
            IndexCategory indexCategory = null;
            if (!string.IsNullOrEmpty(Id))
            {
                indexCategory = m_IndexCategoryServices.GetById( Id);
            }
            return View(indexCategory);
        }
        #endregion

        #region JsonResult

        public JsonResult GetIndexCategoryList(int limit, int offset, string Name,  string remarks,
          DateTime? startTime, DateTime? endTime )
        {
            var jsonData = new Object();
            var lstRes = new List<IndexCategory>();
            int total = 0;
            lstRes = m_IndexCategoryServices.GetAllIndexCategorys( limit, offset, Name,  remarks, startTime, endTime,  out total);
            return Json(new { total = total, rows = lstRes }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult EditIndexCategory(FormCollection collection)
        {
            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;
            string Id = collection["IndexCateId"];
            IndexCategory indexCategory = new IndexCategory();
            if (!string.IsNullOrEmpty(Id))
            {
                indexCategory = m_IndexCategoryServices.GetById(Id);
            }
            

            HttpRequest request = System.Web.HttpContext.Current.Request;
            HttpFileCollection FileCollect = request.Files;
            UploadFile uf = null;
            if (FileCollect.Count > 0) //如果集合的数量大于0 
            {
                string Virbase = @"Upload\Images\Advertisement\";
                string DataTimeFolder = DateTime.Now.ToString("yyyyMMdd");
                string localpath = AppDomain.CurrentDomain.BaseDirectory + Virbase;
                string Folder = localpath + DataTimeFolder;
                if (!Directory.Exists(Folder))
                {
                    Directory.CreateDirectory(Folder);
                }
                HttpPostedFile FileSave = FileCollect[0]; //用key获取单个文件对象HttpPostedFile 
                uf = new UploadFile();
                uf.FileName = FileSave.FileName;
                uf.FileExt = Path.GetExtension(FileSave.FileName);
                uf.FileSize = FileSave.ContentLength;
                uf.Site = Site;
                uf.ServiceAddress = CommonHelper.GetAppSettings("Domain");
                string guidName = Guid.NewGuid().ToString() + uf.FileExt;
                uf.Path = ("\\" + Virbase + DataTimeFolder + "\\" + guidName).Replace("\\", "/");
                uf.FileId = Guid.NewGuid().ToString();
                string LocalFullPath = Folder + @"\" + guidName;
                uf.LocalFullPath = LocalFullPath;
                FileSave.SaveAs(LocalFullPath); //将上传的东西保存                                                           
                indexCategory.IconImg = uf.Path;
                indexCategory.Domain = uf.ServiceAddress;
            }
            indexCategory.Remarks= collection["Remarks"];
            indexCategory.IndexCateShowName = collection["IndexCateShowName"];
            indexCategory.CategoryID = int.Parse(collection["CategoryID"]);
            
            indexCategory.IndexCateUrl = collection["IndexCateUrl"];
            if (!indexCategory.IndexCateUrl.Contains("?cateId="))
            {
                indexCategory.IndexCateUrl = indexCategory.IndexCateUrl + "?cateId=" + indexCategory.CategoryID;
            }
            indexCategory.Sort = int.Parse(collection["Sort"]);
           
            string enable = collection["Enable"];
            indexCategory.Enable = int.Parse(string.IsNullOrEmpty(enable) ? "0" : ((enable.ToString() == "on") ? "1" : "0"));
            string IsShow = collection["IsShow"];           
            if (!string.IsNullOrEmpty(Id))
            {

                success = m_IndexCategoryServices.EditIndexCategory(uf, indexCategory, this.CurrentUser.UserID.ToString());
            }
            else
            {
                indexCategory.CreateTime = DateTime.Now;
                indexCategory.EndTime = DateTime.Now.AddMonths(12);
                indexCategory.IndexCateId = Guid.NewGuid().ToString();
                success = m_IndexCategoryServices.AddIndexCategory(uf, indexCategory, this.CurrentUser.UserID.ToString());
            }
            if (success) { Cache_IndexCategory.ClearAd_INDEXCATEGORY_KANGDAO(); }
            result = success ? "编辑成功" : "编辑失败";
            jsonData = new { Success = success, Data = result };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        public JsonResult DelIndexCategory(string Id)
        {
            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;

            IndexCategory indexCategory = new IndexCategory();
            if (!string.IsNullOrEmpty(Id))
            {
                indexCategory = m_IndexCategoryServices.GetById( Id);
                success = m_IndexCategoryServices.DelIndexCategory(indexCategory);
            }
            if (success) { Cache_IndexCategory.ClearAd_INDEXCATEGORY_KANGDAO(); }
            result = success ? "删除成功" : "删除失败";
            jsonData = new { Success = success, Data = result };
            return Json(jsonData, JsonRequestBehavior.AllowGet);

        }
        #endregion
    }
}